import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tiktokadult/alert_business/splash/update_dialog.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/config/config.dart';
import 'package:tiktokadult/hj_page/mine_business/identity/mine_identity_page.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_setting/bing_phone_page.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_setting/invite_bind_view.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_setting/mine_setting_profile_page.dart';
import 'package:tiktokadult/hj_page/mine_business/more_question/mine_qa_page.dart';
import 'package:tiktokadult/hj_page/mine_business/widgets/no_permission_dialog.dart';
import 'package:tiktokadult/hj_utils/global.dart';
import 'package:tiktokadult/hj_utils/version_util.dart';
import 'package:tiktokadult/hj_utils/video_cache_manager.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/tools_base/cache/cache_util.dart';
import 'package:tiktokadult/tools_base/cache/image_cache_manager.dart';
import 'package:tiktokadult/tools_base/global_store/store.dart';
import 'package:tiktokadult/tools_base/image/image_data_handle/image_cache_disk.dart';
import 'package:tiktokadult/tools_base/video_download/video_download_manager.dart';
import 'package:tiktokadult/tools_base/widget/net_image_widget.dart';

import 'mine_find_account_page.dart';
import 'setting_avatar_page.dart';

class SettingModel {
  final String? title;
  final bool showAvatar;
  final bool showNickName;
  final String? subTitle;
  final bool showCopy;
  final bool canPush;
  final int index;

  SettingModel(
      {this.title,
      this.showAvatar = false,
      this.subTitle,
      this.showCopy = false,
      this.canPush = true,
      this.showNickName = false,
      this.index = -1});
}

class MineSettingPage extends StatefulWidget {
  static const String routeName = '/mine_setting';
  const MineSettingPage({super.key});

  @override
  State<MineSettingPage> createState() => _MineSettingPageState();
}

class _MineSettingPageState extends State<MineSettingPage> {
  late final dataSource = <SettingModel>[];

  String cacheSize = ''; // 缓存大小

  @override
  void initState() {
    super.initState();
    getCacheSize();
  }

  Future<void> getCacheSize() async {
    try {
      cacheSize = await loadCache();
      setState(() {});
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('设置中心')),
      body: Container(
        decoration: BoxDecoration(
          color: Colors.white.withOpacity(.05),
          borderRadius: BorderRadius.circular(8),
        ),
        margin: EdgeInsets.only(
          left: 10,
          top: 12,
          right: 10,
        ),
        child: ListView(
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          children: [
            _buildItem(
                title: '头像',
                showAvatar: true,
                onTap: () {
                  if (!globalStore.isVIP()) {
                    Get.dialog(SettingNoPermissionDialog(
                      content: '您还不是VIP无法修改头像',
                      subContent: '开通会员 即可解锁继续',
                      showCancel: false,
                    ));
                    return;
                  }
                  Get.toNamed(SettingAvatarPage.routeName);
                }),
            _buildLine(),
            _buildItem(
                title: '昵称',
                subTitle: context.watch<GlobalStore>().meInfo?.name,
                onTap: () {
                  if (!globalStore.isVIP()) {
                    Get.dialog(SettingNoPermissionDialog(
                      content: '您还不是VIP无法修改昵称!',
                      subContent: '开通会员 即可解锁继续',
                      showCancel: false,
                    ));
                    return;
                  }
                  Get.toNamed(SettingProfilePage.routeName, arguments: SettingProfileType.nickName);
                }),
            _buildLine(),
            _buildItem(
                title: '${Config.APPNAME}ID',
                subTitle: context.watch<GlobalStore>().meInfo?.uid.toString(),
                showCopy: true,
                cashPush: false,
                onTap: () {}),
            _buildLine(),
            _buildItem(
                title: '手机号码',
                subTitle:
                    (context.watch<GlobalStore>().meInfo?.mobile ?? '').isEmpty ? '立即绑定' : '${context.watch<GlobalStore>().meInfo?.mobile}',
                onTap: () {
                  Get.toNamed(BindPhonePage.routeName);
                }),
            _buildLine(),
            _buildItem(
                title: '账号找回',
                onTap: () {
                  Get.to(() => MineFindAccountPage());
                }),
            _buildLine(),
            _buildItem(
                title: '邀请码',
                subTitle: (context.watch<GlobalStore>().meInfo?.inviterCode ?? '').isEmpty
                    ? '未设置'
                    : '${context.watch<GlobalStore>().meInfo?.inviterCode}',
                onTap: () {
                  if ((context.watch<GlobalStore>().meInfo?.inviterCode ?? '').isEmpty) {
                    Get.to(() => InviteBindPage());
                  } else {
                    showToast('您已绑定过邀请码');
                  }
                }),
            _buildLine(),
            _buildItem(
                title: '账号凭证',
                showAvatar: false,
                onTap: () {
                  Get.to(() => MineAccountIdentityPage());
                }),
            _buildLine(),
            _buildItem(
                title: '常见问题',
                showAvatar: false,
                onTap: () {
                  Get.to(() => MineQAPage());
                }),
            _buildLine(),
            _buildItem(
                title: '清除缓存',
                subTitle: cacheSize,
                onTap: () async {
                  await VideoDownloadManager.instance.emptyCache();
                  await ImageCacheDisk.emptyCache();
                  await VideoCacheManager().emptyCache();
                  await ImageCacheManager().emptyCache();
                  cacheSize = "0.0KB";
                  if (mounted) setState(() {});
                  showToast('清理缓存成功');
                }),
            _buildLine(),
            _buildItem(
                title: '检查更新',
                subTitle: 'V${Config.innerVersion}',
                onTap: () async {
                  var versionMap = await checkUpdate();
                  if (versionMap.isNotEmpty) {
                    Get.dialog(UpdateDialog(updateInfo: versionMap['versionBean']), barrierDismissible: false);
                  } else {
                    showToast("当前已是最新版！");
                  }
                }),
            _buildLine(),
          ],
        ),
      ),
    );
  }

  _buildLine() {
    return Padding(
      padding: EdgeInsets.only(left: 16),
      child: Divider(
        height: .5,
        color: Colors.white.withOpacity(.05),
      ),
    );
  }

  Widget _buildItem({
    String title = '',
    String? subTitle,
    bool showCopy = false,
    bool showAvatar = false,
    VoidCallback? onTap,
    bool cashPush = true,
  }) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: onTap,
      child: Container(
        height: 56,
        padding: EdgeInsets.symmetric(horizontal: 12),
        child: Row(
          children: [
            Text(
              title,
              style: TextStyle(color: Colors.white.withOpacity(0.9), fontSize: 14),
            ),
            Spacer(),
            if (showAvatar)
              NetworkImageLoader(
                imageUrl: context.watch<GlobalStore>().meInfo?.portrait ?? '',
                width: 24,
                height: 24,
                borderRadius: 12,
              ),
            if (subTitle != null)
              Text(
                subTitle,
                style: TextStyle(color: Color(0xFF656565), fontSize: 12),
              ),
            if (showCopy) ...[
              4.sizeBoxW,
              GestureDetector(
                onTap: () {
                  Clipboard.setData(ClipboardData(text: '${globalStore.meInfo?.uid}'));
                  showToast('复制成功');
                },
                child: Image.asset(
                  'mine_copy.png'.mineImgPath,
                  width: 24,
                ),
              ),
            ],
            if (!showCopy) ...[
              10.sizeBoxW,
              Icon(
                Icons.arrow_forward_ios_rounded,
                size: 14,
                color: Color(0xFFDCDCDC),
              ),
            ]
          ],
        ),
      ),
    );
  }
}
